package com.wangshouyu.mp.media;

import com.google.common.io.ByteStreams;
import com.wangshouyu.mp.base.request.HttpMethod;
import com.wangshouyu.mp.base.request.MpClient;
import com.wangshouyu.mp.base.request.RequestBody;
import com.wangshouyu.mp.base.request.ResponseBody;
import com.wangshouyu.mp.utils.GsonUtils;

import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;

import static com.wangshouyu.mp.base.constant.UrlConstant.MEDIA_LIST_URL;
import static com.wangshouyu.mp.base.constant.UrlConstant.UPLOAD_TMP_MEDIA_URL;

/**
 * @author 王守钰
 * @date 2020年12月22日 16:03
 * @description 素材处理器
 */
public class MediaHandler {

    private MediaHandler() {
    }

    /**
     * 上传素材
     * @param client 客户端
     * @param accessToken token
     * @param mediaType 素材类型
     * @param inputStream 输入流
     * @param fileName 文件名
     * @return 返回结果
     * @throws IOException
     */
    public static MediaInfo upload(MpClient client,
                                   String accessToken,
                                   MediaType mediaType,
                                   InputStream inputStream,
                                   String fileName) throws IOException {
        String url = MessageFormat.format(UPLOAD_TMP_MEDIA_URL, accessToken, mediaType.getType());
        return client.request(
                HttpMethod.POST,
                url,
                RequestBody.create(ByteStreams.toByteArray(inputStream),fileName),
                MediaInfo.class);
    }

    /**
     * 素材列表
     * @param client 客户端
     * @param request 请求信息
     * @param accessToken token
     * @return 数据列表
     */
    public static MediaListResponse list(MpClient client, MediaListRequest request, String accessToken){
        String url = MessageFormat.format(MEDIA_LIST_URL, accessToken);
        return client.request(
                HttpMethod.POST,
                url,
                RequestBody.create(GsonUtils.toJson(request), ResponseBody.UTF_8),
                MediaListResponse.class);
    }
}
